#pragma once
#include "net.h"
#include "message.h"

namespace rpc
{
    class callback
    {
    public:
        using ptr = std::shared_ptr<callback>;
        virtual void onMessage(const BaseConnection::ptr &conn, BaseMessage::ptr &msg) = 0;
    };
    template <typename T>
    class callbackT
    {
    public:
        using ptr = std::shared_ptr<callbackT<T>>;
        using MessageCallback = std::function<void(const BaseConnection::ptr &conn, std::shared_ptr<T> &msg)>;
        callbackT(const MessageCallback &handler)
            : _handler(handler)
        {
        }
        void onMesage(const BaseConnection::ptr &conn, BaseMessage::ptr &msg) override
        {
            auto type_msg = std::dynamic_pointer_cast<T>(msg);
            _handler(conn, type_msg);
        }

    private:
        MessageCallback _handler;
    };
    class dispather
    {
    public:
        using ptr = std::shared_ptr<dispather>;
        template <typename T>
        void registerHandler(MType mtype, const typename callbackT<T>::MessageCallback &handler)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _handlers.insert(std::make_pair(mtype, msg));
        }
        void onMessage(const BaseConnection::ptr &conn, BaseMessage::ptr &msg)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _handlers.find(msg->mtypes());
            if (it != _handlers.end())
            {
                return it->second->onMessage(conn, msg);
            }
            ELOG("收到未知类型!");
            conn->shutdown();
        }

    private:
        std::unordered_map<MType, callback::ptr> _handlers;
        std::mutex _mutex;
    };
}